<?php

namespace lemon\models\traits;

use Yii;
use yii\web\UploadedFile;
use lemon\repository\FileHelper;

/**
 * 
 */
trait ModelTrait
{
	public $save_path = '/uploads/picture/';
	
	/**
	 * 保存model通用方法
	 * @param yii\db\ActiveRecord $model
	 * @param string $msg
	 * @throws \Exception
	 */
	public function savedb(&$model, $msg=''){
		if(!$model->save()){
			$error = array_values($model->getFirstErrors())[0].(!empty($msg)?"[{$msg}]":'');
			throw new \Exception($error);
		}
	}
	
	/**
	 *
	 * @param unknown $model
	 * @param unknown $field
	 * @throws \Exception
	 * @return string
	 */
	public function saveImage($model, $field){
		$upload_file = UploadedFile::getInstance($model, $field);
		if ($upload_file) {
			$files = [$upload_file];
			
			$saved_file = FileHelper::storeFile($files);
			if(count($saved_file) == 1 && $saved_file[0]['result']){
				return $saved_file[0]['file'];
			}
			return '';
		}
		return '';
	}
	
}